import Koa from "koa";
import Router from "koa-router";
import { NlpPkg } from "utils";
import { matchModel, AnalysisResult } from "utils";
import { PassThrough } from "stream";
import sse from "koa-sse-stream";

const app = new Koa();
const router = new Router();

type Result = {
  code: number;
  data: any;
};
app.use(async (ctx, next) => {
  ctx.set("Access-Control-Allow-Origin", "*");
  ctx.set("Access-Control-Allow-Headers", "content-type");
  ctx.set("Access-Control-Allow-Methods", "OPTIONS,GET,PUT,POST,DELETE");
  await next();
});

app.use(async (ctx: Koa.Context, next) => {
  if (ctx.path !== "/sse") {
    return await next();
  }
  setInterval(() => {
    ctx.sse.send("a notice");
    // ctx.sse.sendEnd();
  }, 3000);
});

app.use(router.routes());
app.use(router.allowedMethods());
router.get("/test", async (ctx: Koa.Context) => {
  const queryText = ctx.query["text"];
  const nlpPkg = new NlpPkg({
    xfAccount: {
      APPID: "554602d6",
      APIKEY: "117d03095264db3af60c571188fb2258",
    },
    nlpApi: ["cws", "pos", "dp"],
    // text: "帮我查一下济南市历下区高新管委会街道地下管线信息",
    text: queryText.toString(),
  });
  const res = await nlpPkg.getNlpResult();
  // TODO: 可以优化 细分结构
  const resultTemplate = matchModel(<AnalysisResult>res, [
    "actionKeywords",
    "targetKeywords",
  ]);
  let result: Result;
  if (resultTemplate) {
    result = {
      code: 0,
      data: resultTemplate,
    };
  } else {
    result = {
      code: 1,
      data: null,
    };
  }

  ctx.body = result;
});
app.use(
  sse({
    maxClients: 5000,
    pingInterval: 30000,
  }),
);
app.listen(3000, () => {
  console.log("Server is running at http://localhost:3000");
});

// (async () => {
//   const nlpPkg = new NlpPkg({
//     xfAccount: {
//       APPID: "554602d6",
//       APIKEY: "117d03095264db3af60c571188fb2258",
//     },
//     nlpApi: ["cws", "pos", "dp"],
//     // text: "帮我查一下济南市历下区高新管委会街道地下管线信息",
//     text: "查寻一下济南市历下区会展路地下管线",
//   });
//   const res = await nlpPkg.getNlpResult();
//   console.log(res);
//   // TODO: 可以优化 细分结构
//   const resultTemplate = matchTemplate(<AnalysisResult>res, [
//     "actionKeywords",
//     "targetKeywords",
//   ]);
//   console.log(resultTemplate);
// })();
